#include "mbappwig.h"
#include "ui_mbappwig.h"
#include <globalval.h>
#include <QMessageBox>
#include <QFileDialog>
#include <QDateTime>

MbappWig::MbappWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MbappWig)
    , udpSocket(new QUdpSocket(this))
    , frameTimer(new QTimer(this))
    , isStreaming(false)
{
    ui->setupUi(this);

    // 设置UI初始状态
    ui->stopButton->setEnabled(false);
    // 连接信号槽
    connect(udpSocket, &QUdpSocket::readyRead, this, &MbappWig::readPendingDatagrams);
    connect(frameTimer, &QTimer::timeout, this, &MbappWig::displayFrame);

}

MbappWig::~MbappWig()
{
    delete ui;
}

void MbappWig::on_connectButton_clicked()
{
    // 获取服务器地址和端口
    serverAddress = QHostAddress(GlobalVal::IP);
    serverPort =ui->port_lineEdit->text().toShort();

    if (serverAddress.isNull() || serverPort == 0) {
        QMessageBox::warning(this, "错误", "请输入有效的服务器地址和端口");
        return;
    }

    startStreaming();
}

void MbappWig::on_captureButton_clicked()
{
    if (!isStreaming) {
        QMessageBox::warning(this, "错误", "请先连接到视频流");
        return;
    }

    // 弹出保存文件对话框
    QString fileName = QFileDialog::getSaveFileName(this, "保存图片",
                                                   QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".jpg",
                                                   "JPEG图像 (*.jpg *.jpeg)");

    if (!fileName.isEmpty()) {
        // 发送捕捉照片指令
        QByteArray datagram = "get_photo " + fileName.toUtf8();
        udpSocket->writeDatagram(datagram, serverAddress, serverPort);
    }
    // 保存当前帧到指定路径
        if (!currentFrame.save(fileName, "JPEG")) {
            QMessageBox::warning(this, "错误", "保存图片失败");
        } else {
            QMessageBox::information(this, "成功", "图片已保存: " + fileName);
        }
}

void MbappWig::on_stopButton_clicked()
{
    stopStreaming();
}
void MbappWig::startStreaming()
{
    // 发送开始流指令
    QByteArray datagram = "get_stream";
    udpSocket->writeDatagram(datagram, serverAddress, serverPort);

    isStreaming = true;
    ui->connectButton->setEnabled(false);
    ui->stopButton->setEnabled(true);
    ui->statusLabel->setText("状态: 正在接收视频流...");

    // 启动定时器显示帧
    frameTimer->start(33); // 约30fps
}

void MbappWig::stopStreaming()
{
    if (isStreaming) {
        // 发送停止流指令
        QByteArray datagram = "stop_stream";
        udpSocket->writeDatagram(datagram, serverAddress, serverPort);

        frameTimer->stop();
        isStreaming = false;
        ui->connectButton->setEnabled(true);
        ui->stopButton->setEnabled(false);
        ui->statusLabel->setText("状态: 已断开连接");
        ui->videoLabel->clear();

    }
}
void MbappWig::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());

        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 检查是否是服务器响应
        if (sender != serverAddress || senderPort != serverPort) {
            continue;
        }

        // 处理文本响应
        if (datagram.startsWith("stream_started")) {
            ui->statusLabel->setText("状态: 视频流已启动");
        }
        else if (datagram.startsWith("stream_stopped")) {
            stopStreaming();
        }
        else if (datagram.startsWith("error:")) {
            QMessageBox::warning(this, "错误", QString::fromUtf8(datagram));
        }
        else if (datagram.endsWith(".jpg") || datagram.endsWith(".jpeg")) {
            QMessageBox::information(this, "成功", "图片已保存: " + QString::fromUtf8(datagram));
        }
        // 否则认为是图像数据
        else {
            saveImage(datagram);
        }
    }
}
void MbappWig::saveImage(const QByteArray &imageData)
{
    // 保存当前帧数据
    currentFrame = QImage::fromData(imageData, "JPEG");

    if (currentFrame.isNull()) {
        qDebug() << "无法解析图像数据";
        return;
    }
}

void MbappWig::displayFrame()
{
    if (!currentFrame.isNull()) {
        // 在QLabel上显示图像
        ui->videoLabel->setPixmap(
            QPixmap::fromImage(currentFrame)
            .scaled(ui->videoLabel->size(),
                    Qt::KeepAspectRatio,
                    Qt::SmoothTransformation)
        );
    }
}
